package phone.qyg.com.qyg.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.JSONTool;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.Map;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Third;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2017/12/2 14:58
 * 邮箱：lanbuhan@163.com
 * 功能：登录
 */
@ContentView(R.layout.login)
public class LoginActivity extends BaseActivity implements TextWatcher {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.login)
    TextView login;

    @ViewInject(R.id.regis)
    TextView regis;

    @ViewInject(R.id.forget_pas)
    TextView forget_pas;

    @ViewInject(R.id.weixin)
    TextView weixin;

    @ViewInject(R.id.qq)
    TextView qq;

    @ViewInject(R.id.phone)
    EditText phone;

    @ViewInject(R.id.password)
    EditText password;

    ProgressDialog dialog;


    @Event(value = {R.id.back,R.id.login,R.id.regis,R.id.forget_pas,
                    R.id.weixin,R.id.qq})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.login:
                String phoneStr = getEditToString(phone);
                String passwordStr = getEditToString(password);

                if (!isRequestStr(phoneStr) || !isRequestStr(passwordStr)) {
                    PromptManager.showToast(R.string.phone_password_no);
                } else {
                    login.setEnabled(false);
                    getLogin(phoneStr, passwordStr);
                }
                break;
            case R.id.regis:
                TransformController.transformController(QXApplication.getContext(),ReigsActivity.class);
                break;
            case R.id.forget_pas:
                TransformController.transformController(QXApplication.getContext(),ForgetPassActivity.class);
                break;
            case R.id.weixin:
                //微信登录
                PromptManager.showToast("暂未开通,尽情期待!");
//                if (UMShareAPI.get(mContext).isAuthorize(LoginActivity.this, SHARE_MEDIA.WEIXIN)) {
//                    UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, infoauthListener);
//                } else {
//                    UMShareAPI.get(mContext).doOauthVerify(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
//                }
                break;
            case R.id.qq:
                //QQ登录
                PromptManager.showToast("暂未开通,尽情期待!");
//                boolean isauth = UMShareAPI.get(mContext).isAuthorize(LoginActivity.this, SHARE_MEDIA.QQ);
//                if (isauth) {
//                    UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, infoauthListener);
//                } else {
//                    UMShareAPI.get(mContext).doOauthVerify(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
//                }
                break;
        }
    }

    private void getLogin(String phone, String password) {
        mapKeys.put(AppHttpKey.LOGIN_NAME, phone);
        mapKeys.put(AppHttpKey.PASSWORD, password);
        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.DOLOGIN,
                mapKeys,
                new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        login.setEnabled(true);
                        if (JSONTool.isStatus(result)) {
                            loginSucess(result);
                        } else {
                            PromptManager.showToast(JSONTool.jsonDefaluTranString(result, JSONTool.Enum.MESSAGE));
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        login.setEnabled(true);
                    }
                });
    }

    /**
     * 登录成功
     *
     * @param result
     */
    private void loginSucess(String result) {

        try {
            SharePrefUtil.saveString(SharePrefUtil.KEY.APP_USER, JSONTool.requestJSONStringKey(result, JSONTool.Enum.DATA));
            Intent intent = new Intent(ApplicationConfig.APP_QX_LOGIN);
            intent.putExtra(TransformController.ChangeKEY.INTENT_KEY, result);
            LocalBroadcastManager.getInstance(QXApplication.getContext()).sendBroadcast(intent);
            PromptManager.showToast(R.string.login_sucess);
        } catch (Exception e) {

        } finally {
            LoginActivity.this.finish();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            SocializeUtils.safeShowDialog(dialog);
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            SocializeUtils.safeCloseDialog(dialog);
            UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, platform, infoauthListener);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            SocializeUtils.safeCloseDialog(dialog);
//            Toast.makeText(mContext, "失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
            SystemPrintl.systemPrintl(".失败." + t.getMessage());
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            SocializeUtils.safeCloseDialog(dialog);
        }
    };

    UMAuthListener infoauthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onComplete(final SHARE_MEDIA platform, int action, Map<String, String> data) {
            String temp = "";

            final String uid = data.get("uid");
            final String openid = data.get("openid");
            final String name = data.get("name");
            final String iconurl = data.get("iconurl");
            final String gender = data.get("gender");

            //信息获取成功 进行解除操作
            UMShareAPI.get(mContext).deleteOauth(LoginActivity.this, platform, null);

            //int bind_type, int login_type, String head_photo, String nick_name, String sexName, String unionid

            mapKeys.put(AppHttpKey.UNION_ID, uid);
            mapKeys.put(AppHttpKey.TYPE, (platform == SHARE_MEDIA.QQ) ? "1" : "2");
            AppHttpRequest.httpRequestDefalut(ApplicationConfig.THIRD_LOGIN_AFTER,
                    mapKeys,
                    new AppHttpRequest.OnAppHttpListener() {
                        @Override
                        public void onAppHttpState(boolean isState, String result) {
                            Third third = new Third((platform == SHARE_MEDIA.QQ) ? 1 : 2, iconurl, name, gender, uid);
                            if (JSONTool.isStatus(result)) {
                                //0-成功，当前第三方已绑定用户，直接登录
                                loginSucess(result);
                            } else {
                                //1 没有关注过
                                TransformController.transformControllerModel(QXApplication.getContext(), ThirdPartySelectActivity.class, third);
                            }
                        }
                    });
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {

        }
    };

    @Override
    public void initSucessView() {
        dialog = new ProgressDialog(this);
    }
    @Override
    public void initData(Bundle savedInstanceState) {}

    @Override
    public void initViewHandler() {
        phone.addTextChangedListener(this);
        password.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//        login.setEnabled(false);
//        login.setBackgroundResource(R.drawable.ash_btn_frame);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(isEmptyOrHint(phone,R.string.login_phone_name_hint) &&
                isEmptyOrHint(password,R.string.please_password)){
            login.setEnabled(true);
            login.setBackgroundResource(R.drawable.blue_btn_frame);
        }else{
            login.setEnabled(false);
            login.setBackgroundResource(0);
            login.setBackgroundResource(R.drawable.ash_btn_frame);

        }
    }

    @Override
    public void afterTextChanged(Editable s) {}
}
